﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Windows.Forms;
using BusinessObjects.Constants;
using BusinessServices;
using CarLeaseManageSystem.Properties;
using Core.Utilities;
using DataEntities;

namespace CarLeaseManageSystem
{
    public partial class FormYuZuMana : Form
    {
        private readonly KeHuService _keHuService;
        private readonly YuZuService _yuZuService;
        private readonly CarService _carService;
        private readonly XuZuService _xuZuService;

        private List<XuZuInfo> _xuZuInfoCache;
        private List<int> newKeHuIdsCache = new List<int>();
        private List<CarInfo> carInfoCache = new List<CarInfo>();

        public FormYuZuMana()
        {
            _keHuService = new KeHuService();
            _yuZuService = new YuZuService();
            _carService = new CarService();
            _xuZuService = new XuZuService();
            InitializeComponent();
        }

        private void FormYuZuMana_Load(object sender, EventArgs e)
        {
            _xuZuInfoCache = _xuZuService.GetActiveXuZuInfo();
            var yuZuInfo = _yuZuService.GetAll();
            var def = new List<object> { new { 编号 = -1, 客户 = "(无预租信息)", 车型 = string.Empty, 预付 = 0, 预租日期 = DateTime.Now, 车照 = Resources.car2 } }.AsQueryable();

            if (yuZuInfo.Count == 0)
            {
                bindingSource1.DataSource = def;
            }
            else
            {
                bindingSource1.DataSource = yuZuInfo.Select(y => new
                {
                    编号 = y.iYZDId,
                    客户 = y.KeHuInfo.sName,
                    车型 = y.CarInfo.sCType,
                    预付 = y.dYuFuJE,
                    预租日期 = y.tYZDate,
                    车照 = y.CarInfo.mCPhoto
                }).AsQueryable();
            }
            bindingNavigator1.BindingSource = bindingSource1;
            comBoxName.DataBindings.Clear();
            comBoxCar.DataBindings.Clear();
            numericYF.DataBindings.Clear();
            dateYuDing.DataBindings.Clear();
            pictBoxCar.DataBindings.Clear();
            comBoxName.DataBindings.Add(new Binding("Tag", bindingSource1, "编号"));
            comBoxName.DataBindings.Add(new Binding("Text", bindingSource1, "客户"));
            comBoxCar.DataBindings.Add(new Binding("Text", bindingSource1, "车型"));
            numericYF.DataBindings.Add(new Binding("Value", bindingSource1, "预付"));
            dateYuDing.DataBindings.Add(new Binding("Value", bindingSource1, "预租日期"));
            Binding b = new Binding("Image", bindingSource1, "车照");
            b.Format += new ConvertEventHandler(ConvertCarImage);
            pictBoxCar.DataBindings.Add(b);
            btnOk.Text = "新建";

            tBtnDel.Enabled = tBtnRefur.Enabled = btnUpdate.Enabled = true;

        }

        private void ConvertCarImage(object sender, ConvertEventArgs e)
        {
            try
            {
                e.Value = ((Binary) e.Value).ToImage();
            }
            catch
            {
                e.Value = Resources.car2;
            }
        }

        private void LoadKeHuInfo()
        {
            comBoxName.Items.Clear();
            newKeHuIdsCache.Clear();
            var newKeHuInfo = _keHuService.GetNewKeHuInfo();
            foreach (KeHuInfo keHuInfo in newKeHuInfo)
            {
                comBoxName.Items.Add(string.Format("{0}({1})", keHuInfo.sName, keHuInfo.sIdCard.Substring(14, 4)));
                newKeHuIdsCache.Add(keHuInfo.iKeHuId);
            }
        }

        private void LoadCarInfo()
        {
            var freeCars = _carService.GetFreeCars();
            var rentingCars = _carService.GetRentingCars();
            comBoxCar.Items.Clear();
            carInfoCache.Clear();

            if (freeCars.Count > 0)
            {
                comBoxCar.Items.Add("***空闲车辆***");
                carInfoCache.Add(new CarInfo());
                foreach (CarInfo carInfo in freeCars)
                {
                    comBoxCar.Items.Add(string.Format("{0}({1})", carInfo.sCType, carInfo.sCPId));
                    carInfoCache.Add(carInfo);
                }
            }

            if (rentingCars.Count > 0)
            {
                comBoxCar.Items.Add("***租出车辆***");
                carInfoCache.Add(new CarInfo());
                foreach (CarInfo carInfo in rentingCars)
                {
                    comBoxCar.Items.Add(string.Format("{0}({1})", carInfo.sCType, carInfo.sCPId));
                    carInfoCache.Add(carInfo);
                }
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            ComboBox oldComBoxName = new ComboBox();
            ComboBox oldComBoxCar = new ComboBox();
            if (btnOk.Text == "新建")
            {
                comBoxName.Tag = null;
                comBoxName.Text = string.Empty;
                comBoxCar.Text = string.Empty;
                numericYF.Value = 0;
                bindingNavigator1.Enabled = btnUpdate.Enabled = false;
                dateYuDing.Value = DateTime.Now;
                if (oldComBoxName.Items.Count != 0)
                {
                    comBoxName = oldComBoxName;
                    comBoxCar = oldComBoxCar;
                }
                else
                {
                    LoadKeHuInfo();
                    LoadCarInfo();
                }
                btnOk.Text = "保存";
                return;
            }
            if (btnOk.Text == "保存")
            {
                if (comBoxName.SelectedIndex == -1 || comBoxCar.SelectedIndex == -1 || numericYF.Value == 0)
                {
                    if (MessageBox.Show(YuZuConstant.BaseInfoLost, "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error) == DialogResult.OK)
                    {
                        return;
                    }
                    FormYuZuMana_Load(sender, e);
                }
                else
                {
                    var newYuZuInfo = new YuZuInfo
                    {
                        iCarid = carInfoCache[comBoxCar.SelectedIndex].iCarid,
                        iKeHuId = newKeHuIdsCache[comBoxName.SelectedIndex],
                        dYuFuJE = (double)numericYF.Value,
                        tYZDate = dateYuDing.Value
                    };

                    newYuZuInfo = _yuZuService.Add(newYuZuInfo);
                    if (newYuZuInfo.iYZDId > 0)
                    {
                        MessageBox.Show(YuZuConstant.AddSucceed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show(YuZuConstant.AddFailed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }

                foreach (var t in comBoxName.Items)
                {
                    oldComBoxName.Items.Add(t);
                }

                foreach (var t in comBoxCar.Items)
                {
                    oldComBoxCar.Items.Add(t);
                }

                comBoxName.Items.Clear();
                comBoxCar.Items.Clear();
                FormYuZuMana_Load(sender, e);
                bindingNavigator1.Enabled = btnUpdate.Enabled = true;
            }
        }

        private void comBoxCar_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (comBoxCar.SelectedItem.ToString() == "***空闲车辆***" || comBoxCar.SelectedItem.ToString() == "***租出车辆***")
                {
                    comBoxCar.SelectedIndex++;
                    return;
                }

                var index = comBoxCar.SelectedIndex;
                var lastXuZuInfo = _xuZuInfoCache.FirstOrDefault(x => x.ChuZuInfo.iCarid == carInfoCache[comBoxCar.SelectedIndex].iCarid);

                pictBoxCar.Image = carInfoCache[index].mCPhoto.ToImage();

                dateYuDing.Value = lastXuZuInfo != null ? lastXuZuInfo.tNewDate.AddDays(1).Date : DateTime.Now.Date;
            }
            catch { }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (btnUpdate.Text == "更新")
            {
                LoadCarInfo();
                btnUpdate.Text = "保存";
                bindingNavigator1.Enabled = comBoxName.Enabled = btnOk.Enabled = false;
                return;
            }

            if (btnUpdate.Text == "保存" && comBoxName.Tag != null)
            {
                var yzdId = (int)comBoxName.Tag;
                YuZuInfo updateResult;
                if (comBoxCar.SelectedIndex != -1)
                {
                    updateResult = _yuZuService.Update(yzdId, yuZu =>
                    {
                        yuZu.iCarid = carInfoCache[comBoxCar.SelectedIndex].iCarid;
                        yuZu.dYuFuJE = (double)numericYF.Value;
                        yuZu.tYZDate = dateYuDing.Value;
                    });
                }
                else
                {
                    updateResult = _yuZuService.Update(yzdId, yuZu =>
                     {
                         yuZu.dYuFuJE = (double)numericYF.Value;
                         yuZu.tYZDate = dateYuDing.Value;
                     });
                }

                if (updateResult != null && updateResult.iYZDId > 0)
                {
                    MessageBox.Show(YuZuConstant.UpdateSucceed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    btnUpdate.Text = "更新";
                    FormYuZuMana_Load(sender, e);
                    bindingNavigator1.Enabled = comBoxName.Enabled = btnOk.Enabled = true;
                    return;
                }
                MessageBox.Show(YuZuConstant.UpdateFailed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tBtnRefur_Click(object sender, EventArgs e)
        {
            FormYuZuMana_Load(sender, e);
        }

        private void tBtnDel_Click(object sender, EventArgs e)
        {
            if (comBoxName.Tag != null)
            {
                var isDeleted = _yuZuService.Delete((int)comBoxName.Tag);
                if (isDeleted)
                {
                    MessageBox.Show(YuZuConstant.DeleteSucceed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    FormYuZuMana_Load(sender, e);
                }
                else
                {
                    MessageBox.Show(YuZuConstant.DeleteFailed, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show(YuZuConstant.FlushAndTryAgain, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
